import React, { Component } from 'react';
import { Modal, message, Select } from 'antd';
import PropTypes from 'prop-types';
import _, { get } from 'lodash';
import OrgCascader from '@components/org-cascader';
import { batchUpdateAssets } from '@api/asset';
import { connect } from 'react-redux';
import { actions as assetManageActions } from '../../reducer';
import { bindActionCreators } from 'redux';
import './index.less';

class EditOrgModal extends Component {
  constructor(props) {
    super(props);
    this.state = _.cloneDeep(EditOrgModal.defaultProps);
  }

  static defaultProps = {
    orgId: '',
    loading: false,
    value: []
  };

  static getDerivedStateFromProps(props) {
    if (!props.visible) {
      const { sites = [] } = props;
      let defaultProps = _.cloneDeep(EditOrgModal.defaultProps);
      let orgArray = _.uniq(sites.map(site => _.get(site, 'organization._id', '')));
      if (orgArray.length === 1 && orgArray[0]) {
        let value = _.get(sites[0], 'organization.paths', []).concat([
          _.get(sites[0], 'organization._id', '')
        ]);
        defaultProps.value = value;
      }
      return defaultProps;
    }
  }

  static propTypes = {
    siteIds: PropTypes.array,
    sites: PropTypes.array,
    loadAssets: PropTypes.func,
    visible: PropTypes.bool,
    onClose: PropTypes.func,
    organizationTree: PropTypes.array,
    onOrgPopupVisibleChange: PropTypes.func,
    role: PropTypes.string,
    withBelongTo: PropTypes.bool,
    title: PropTypes.string,
    staffList: PropTypes.array,
    initStaffList: PropTypes.func,
    changeOrgValue: PropTypes.func,
    onAttrSubmit: PropTypes.func,
    changeStaffValue: PropTypes.func,
    staffValue: PropTypes.string
  };

  componentDidMount() {
    this.props.initStaffList();
  }

  onCascaderChange = orgIds => {
    const { withBelongTo = false, changeOrgValue } = this.props;
    const orgId = orgIds[orgIds.length - 1];
    this.setState(
      {
        orgId,
        value: orgIds
      },
      () => withBelongTo && changeOrgValue(orgId)
    );
  };

  onOk = () => {
    const { orgId } = this.state;
    const { siteIds, loadAssets, onClose, withBelongTo = false, onAttrSubmit } = this.props;
    this.setState({ loading: true });
    if (withBelongTo) {
      // 有所属人员时
      onAttrSubmit();
      this.setState({ loading: false });
      return;
    }
    batchUpdateAssets({ query: { siteIds }, set: { organization: orgId } })
      .then(() => {
        message.success('批量设置所属部门成功!');
        this.setState({ loading: false });
        onClose();
        loadAssets();
      })
      .catch(() => {
        message.error('批量设置所属部门失败!');
        this.setState({ loading: false });
      });
  };

  render() {
    const {
      visible,
      onClose,
      organizationTree = [],
      onOrgPopupVisibleChange,
      role,
      title = '所属部门',
      withBelongTo = false,
      staffList,
      staffValue
    } = this.props;
    const { loading, value } = this.state;
    return (
      <Modal
        maskClosable={false}
        visible={visible}
        title={title}
        onCancel={onClose}
        className="edit-org-modal padding-24 bottom-center no-header-bottom-lines"
        onOk={this.onOk}
        confirmLoading={loading}
      >
        {withBelongTo && (
          <div className="edit-org-modal-content" style={{ marginBottom: 15 }}>
            <div className="item-name">所属人员</div>
            <Select
              style={{ width: '100%' }}
              placeholder="请选择所属人员"
              showSearch
              allowClear
              value={staffValue}
              onChange={staffOid => this.props.changeStaffValue(staffOid)}
            >
              {_.map(staffList, staff => (
                <Select.Option key={staff._id} value={staff._id}>
                  {staff.nickname}
                </Select.Option>
              ))}
            </Select>
          </div>
        )}
        <div className="edit-org-modal-content">
          <div className="item-name">所属部门</div>
          <OrgCascader
            onChange={this.onCascaderChange}
            options={organizationTree}
            value={value}
            onOrgPopupVisibleChange={onOrgPopupVisibleChange}
          />
        </div>
        {role === '安全管理员' ? (
          <a className="goto-manage" href="/asset-config/organization" target="_blank">
            前往设置组织架构
          </a>
        ) : (
          <span className="goto-manage">可联系管理员进行组织架构设置</span>
        )}
      </Modal>
    );
  }
}

const mapStateToProps = state => {
  return {
    role: _.get(state, 'auth.user.role', ''),
    staffList: get(state, 'assetManage.staffList', []),
    organizationTree: get(state, 'assetManage.organizationTree', [])
  };
};

const mapDispatchToProps = dispatch => {
  return {
    ...bindActionCreators(assetManageActions, dispatch)
  };
};

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(EditOrgModal);
